#include "Model.h"

Model::Model()
{
}

Model::~Model()
{
    delete mVertexBuffer;
    delete mIndexBuffer;
}

void Model::Init(const char *path)
{
    mVertexBuffer = new VertexBuffer;
    mIndexBuffer = new IndexBuffer;

    FILE *file = fopen(path, "rb");
    fread(&mVertexBuffer->mVertexCount, sizeof(int), 1, file);
    mVertexBuffer->SetSize(mVertexBuffer->mVertexCount);
    fread(mVertexBuffer->mVertexes, sizeof(XVertexData), mVertexBuffer->mVertexCount, file);

    fread(&mIndexBuffer->mIndexCount, sizeof(int), 1, file);
    mIndexBuffer->SetSize(mIndexBuffer->mIndexCount);
    fread(mIndexBuffer->mIndexes, sizeof(unsigned int), mIndexBuffer->mIndexCount, file);

    fclose(file);

    mVertexBuffer->SubmitData();
    mIndexBuffer->SubmitData();
}

void Model::Draw(VkCommandBuffer commandBuffer)
{
    xSetDynamicState(mMaterial->mFixedPipeline, commandBuffer);

    VkBuffer vertexBuffers[] = {mVertexBuffer->mBuffer};
    VkDeviceSize offsets[] = {0};

    vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, mMaterial->mFixedPipeline->mPipeline);
    vkCmdBindVertexBuffers(commandBuffer, 0, 1, vertexBuffers, offsets);
    vkCmdBindIndexBuffer(commandBuffer, mIndexBuffer->mBuffer, 0, VK_INDEX_TYPE_UINT32);
    vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, mMaterial->mFixedPipeline->mPipelineLayout, 0, 1, &mMaterial->mProgram.mDescriptorSet, 0,
                            nullptr);
    vkCmdDrawIndexed(commandBuffer, mIndexBuffer->mIndexCount, 1, 0, 0, 0);
}

void Model::SetMaterial(Material *material)
{
    mMaterial = material;
}